package com.lagou.code.controller;

import com.lagou.code.bean.User;
import com.lagou.code.dao.AuthCodeRepository;
import com.lagou.code.dao.UserRepository;
import com.lagou.edu.service.EmailService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;


@RestController
@RequestMapping()
public class CodeController {

    @Reference(check = false)
    EmailService emailService;

    @Autowired
    UserRepository userRepository;

    @Autowired
    AuthCodeRepository authCodeRepository;

    @GetMapping("create/{email}")
    public boolean getCode(@PathVariable("email") String email) {
        User user = userRepository.findByEmail(email);
        if(user != null){
            return false;
        }
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder sb = new StringBuilder(4);
        for (int i = 0; i < 4; i++) {
            char ch = str.charAt(new Random().nextInt(str.length()));
            sb.append(ch);

        }

        return emailService.sendCode(email, sb.toString());
    }

}
